package com.myproject.shop.controller;

import com.alibaba.fastjson2.JSON;
import com.myproject.shop.domain.Staff;
import com.myproject.shop.service.IStaffService;
import com.myproject.shop.util.AjaxResult;
import com.myproject.shop.util.RedisCache;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;


@Api(tags="Redis测试825")

@RestController
@RequestMapping("/api/redis")
public class RedisController {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IStaffService staffService;

    @ApiOperation("通过Key和Value去和redis设定的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="key",value="key",
            dataType ="String",dataTypeClass = String.class),
            @ApiImplicitParam(name="value",value="value",
                    dataType ="String",dataTypeClass = String.class)

    })
    @GetMapping("/put")
    public AjaxResult put(String key, String value){
        redisCache.setCacheObject(key,value,1, TimeUnit.HOURS);
        String v=(String) redisCache.getCacheObject(key);
        Map<String,Object> result=new HashMap<>();
        result.put("key",key);
        result.put("value",v);
        return AjaxResult.success(result);
    }
    @ApiOperation("传入 id,查询员工信息, 将员工信息放入缓存")
    @ApiImplicitParam( name = "sid", value = "员工ID", required = true,
            dataType = "int", paramType = "query",
            dataTypeClass = int. class)
    @GetMapping("/put0bj")
    public AjaxResult put0bj(@RequestParam int sid) {
        Staff staff = staffService. selectStaffById(sid);
        String jsonStr = JSON. toJSONString(staff);
        redisCache. setCacheObject( String. valueOf(staff. getSid()), jsonStr,
                1, TimeUnit. HOURS);
        return AjaxResult. success(staff);
    }
    @ApiOperation("传入员工 id,从缓存中获取员工信息")
    @ApiImplicitParam( name = "sid", value = "员工ID", required = true,
            dataType = "int", paramType = "query",
            dataTypeClass = int. class)
    @GetMapping("/get0bj")
    public AjaxResult get0bj(@RequestParam int sid) {
        String v = redisCache. getCacheObject( String. valueOf( sid));
        System. out. println(v);
        Staff staff = JSON. parseObject(v, Staff. class);
        return AjaxResult. success(staff);
    }

}

